#include "brequest.h"
#include <algorithm>
#include "butils.h"

using namespace bhttp;

brequest::brequest(brequest::type tp)
    : method_(tp)
{
}

brequest::~brequest()
{
}

void brequest::method(const brequest::type tp)
{
    method_ = tp;
}

const brequest::type brequest::method() const
{
	return method_;
}

void brequest::url(const std::string& url)
{
	url_ = url;
}

void brequest::url(std::string&& url)
{
	url_ = std::move(url);
}

const char* brequest::url() const
{
	return url_.c_str();
}

void brequest::body(const char* buffer, size_t len)
{
    body_.assign(buffer, buffer + len);
}

void brequest::body(const std::string& str)
{
    body_.assign(str.data(), str.data() + str.size());
}

const char* brequest::body() const
{
	return body_.data();
}

size_t brequest::body_size() const
{
	return body_.size();
}

void brequest::headers(const std::vector<std::string>& hds)
{
	headers_ = hds;
}

void brequest::headers(std::vector<std::string>&& hds)
{
	headers_ = std::move(hds);
}

const std::vector<std::string> brequest::headers() const
{
	return headers_;
}

void brequest::header(const std::string& key, const std::string& val)
{
    headers_.erase(std::remove_if(headers_.begin(), headers_.end(), [key](const std::string& head) {
        return std::string::npos != head.find(key); 
    }), headers_.end());
    headers_.emplace_back(key + ":" + val);
}

std::string brequest::header(const std::string& key)
{
    for (const auto& head : headers_)
    {
        std::string k, v;
        butils::split(head, ":", &k, &v);
        if (butils::strip(key) == k)
            return v;
    }
    return std::string();
}

void bhttp::brequest::form(const formpart& fm)
{
	forms_.emplace_back(fm);
}

void bhttp::brequest::form(formpart&& fm)
{
	forms_.emplace_back(std::move(fm));
}

void bhttp::brequest::forms(const std::vector<formpart>& fms)
{
	forms_ = fms;
}

void bhttp::brequest::forms(std::vector<formpart>&& fms)
{
	forms_ = std::move(fms);
}

const std::vector<formpart> bhttp::brequest::forms() const
{
	return forms_;
}
